import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'

// GET /api/courses - 获取所有课程
export async function GET(request: NextRequest) {
    try {
        const { searchParams } = new URL(request.url)
        const includeOrders = searchParams.get('include') === 'orders'

        const courses = await prisma.course.findMany({
            include: includeOrders ? { orders: true } : undefined,
            orderBy: { created_at: 'desc' }
        })

        return NextResponse.json({
            success: true,
            data: courses
        })
    } catch (error) {
        console.error('Error fetching courses:', error)
        return NextResponse.json(
            { success: false, error: 'Failed to fetch courses' },
            { status: 500 }
        )
    }
}

// POST /api/courses - 创建课程
export async function POST(request: NextRequest) {
    try {
        const body = await request.json()

        const {
            name,
            original_price,
            main_pic,
            detail_pic,
            current_price,
            introduction
        } = body

        // 验证必填字段
        if (!name || !original_price || !current_price) {
            return NextResponse.json(
                { success: false, error: 'Missing required fields' },
                { status: 400 }
            )
        }

        const course = await prisma.course.create({
            data: {
                name,
                original_price: Number(original_price),
                main_pic: main_pic || '',
                detail_pic: detail_pic || '',
                current_price: Number(current_price),
                introduction: introduction || ''
            }
        })

        return NextResponse.json({
            success: true,
            data: course
        }, { status: 201 })
    } catch (error) {
        console.error('Error creating course:', error)
        return NextResponse.json(
            { success: false, error: 'Failed to create course' },
            { status: 500 }
        )
    }
}
